/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.logic.db;

import java.util.Iterator;
import java.util.Vector;
import model.logic.nondb.CommonMethods;
import model.pojo.ApplicantCompanies;
import model.pojo.Applicants;
import model.pojo.CareerCategories;
import model.pojo.Countries;
import model.pojo.EducationLevels;
import model.pojo.Grades;
import model.pojo.Industries;
import model.pojo.Institutes;
import model.pojo.Settings;
import model.pojo.StudyFields;
import model.pojo.Users;
import model.pojo.Vacancies;
import model.utils.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Maha
 */
public class UserFunctions {

    /**
     *
     * This is Hibernate Session
     */
    Session session;

    /**
     *
     * Contain Code to get SessionFactory, from ${@link HibernateUtil} class
     */
    public UserFunctions() {
        session = HibernateUtil.getSessionFactory().openSession();
    }

    /**
     * insert user data to user table
     *
     */
    public int register(Users user) {
        int x;
        try {
            session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();
            x = 1;

        } catch (Exception ex) {
            x = 0;
            session.getTransaction().rollback();
            ex.printStackTrace();
        }

        return x;
    }

    public Users login(String email, String password) {
        Users user = null;
        try {
            Criteria criteria = session.createCriteria(Users.class).add(Restrictions.ilike("userEmail", email)).add(Restrictions.ilike("userPassword", password));
            Iterator iterator = criteria.list().iterator();

            while (iterator.hasNext()) {
                user = (Users) iterator.next();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return user;
    }

    public int getPasswordBack(String email, String question, String answer) {
        int x = 0;
        String body;
        Users user = new Users();
        user.setUserEmail(email);
        Criteria getpw = session.createCriteria(Users.class).add(Restrictions.ilike("userEmail", email)).add(Restrictions.ilike("question", question, MatchMode.EXACT)).add(Restrictions.ilike("answer", answer, MatchMode.EXACT));
        Iterator iterator = getpw.list().iterator();
        while (iterator.hasNext()) {
            Users userData = (Users) iterator.next();
            body = "<h2>Dear ," + userData.getUserName() + "</h2><br/>You Requested your lost password,since you proved that u r human not a machine"
                    + "<br/> you can now login using your Email:" + userData.getUserEmail() + "<br/> and <br/>password:" + userData.getUserPassword() + " <br/>Please feel free to login and enjoy our services<br/>Sincerely<br/>GlobiSoft Team";

            CommonWSFunctionality cf = new CommonWSFunctionality();
            Settings settings = cf.getSettings();
            CommonMethods.sendMail(settings.getSmtpUser(), settings.getSmtpPassword(), settings.getSmtpName(), settings.getSmtpUser(), user.getUserEmail(), " Here's Your Password", body);


            //CommonMethods.sendMail(userData.getUserEmail(), "Password Requested", body, "sci.maha@gmail.com", "javanese");
            x = 1;
        }
        return x;
    }

    public int checkEmail(String Email) {
        int x = 0;
        try {
            Criteria criteria = session.createCriteria(Users.class).add(Restrictions.ilike("userEmail", Email));
            Iterator iterator = criteria.list().iterator();

            while (iterator.hasNext()) {
                if (iterator.hasNext() == true) {
                    x = 1;
                }
                break;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return x;
    }

    public Vector<Countries> getCountries() {
        Vector<Countries> count = new Vector<Countries>();
        try {
            Iterator iterator = session.createCriteria(Countries.class).addOrder(Order.asc("countryName")).list().iterator();
            while (iterator.hasNext()) {
                count.add((Countries) iterator.next());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    public Vector<EducationLevels> getEduLevels() {
        Vector<EducationLevels> e = new Vector<EducationLevels>();
        try {
            Iterator iterator = session.createCriteria(EducationLevels.class).list().iterator();
            while (iterator.hasNext()) {
                e.add((EducationLevels) iterator.next());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return e;
    }

    public Vector<Institutes> getInst() {
        Vector<Institutes> count = new Vector<Institutes>();
        try {
            Iterator iterator = session.createCriteria(Institutes.class).addOrder(Order.asc("instituteName")).list().iterator();
            while (iterator.hasNext()) {
                count.add((Institutes) iterator.next());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    public Vector<Grades> getGrades() {
        Vector<Grades> count = new Vector<Grades>();
        try {
            Iterator iterator = session.createCriteria(Grades.class).list().iterator();
            while (iterator.hasNext()) {
                count.add((Grades) iterator.next());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    public Vector<StudyFields> getStudyFields() {
        Vector<StudyFields> count = new Vector<StudyFields>();
        try {
            Iterator iterator = session.createCriteria(StudyFields.class).addOrder(Order.asc("studyFieldName")).list().iterator();
            while (iterator.hasNext()) {
                count.add((StudyFields) iterator.next());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    public Vector<CareerCategories> getCareers() {
        Vector<CareerCategories> count = new Vector<CareerCategories>();
        try {
            Iterator iterator = session.createCriteria(CareerCategories.class).list().iterator();
            while (iterator.hasNext()) {
                count.add((CareerCategories) iterator.next());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    public int insertApplicant(Applicants app) {
        int x = -1;
        try {
            session.beginTransaction();
            session.save(app);
            session.getTransaction().commit();
            Iterator iterator = session.createCriteria(Applicants.class).add(Restrictions.eq("userId", app.getUserId())).list().iterator();
            while (iterator.hasNext()) {
                x = ((Applicants) iterator.next()).getApplicantId();
            }
        } catch (Exception ex) {

            ex.printStackTrace();
        }
        return x;
    }

    public int mergeApplicant(Applicants app) {
        int x = -1;
        try {
            Iterator iterator = session.createCriteria(Applicants.class).add(Restrictions.eq("userId", app.getUserId())).list().iterator();
            while (iterator.hasNext()) {
                x = ((Applicants) iterator.next()).getApplicantId();
            }
            app.setApplicantId(x);
            session.beginTransaction();
            session.merge(app);
            session.getTransaction().commit();

        } catch (Exception ex) {

            ex.printStackTrace();
        }
        return x;
    }

    public int insertApplicantCompanies(ApplicantCompanies comp) {
        int x = 0;
        try {
            session.beginTransaction();
            session.saveOrUpdate(comp);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return x;
    }

    public Applicants getApplicant(double userId) {
        Applicants user = null;
        try {
            Iterator iterator = session.createCriteria(Applicants.class).add(Restrictions.eq("userId", userId)).list().iterator();
            while (iterator.hasNext()) {
                user = (Applicants) iterator.next();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return user;
    }

    public Vector<Industries> getIndustries() {
        Vector<Industries> count = new Vector<Industries>();
        try {
            Iterator iterator = session.createCriteria(Industries.class).list().iterator();
            while (iterator.hasNext()) {
                count.add((Industries) iterator.next());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    public Vector<Vacancies> getVacncies() {
        Vector<Vacancies> count = new Vector<Vacancies>();
        try {
            Iterator iterator = session.createCriteria(Vacancies.class).list().iterator();
            while (iterator.hasNext()) {
                count.add((Vacancies) iterator.next());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    public int updateCompany(ApplicantCompanies company) {
        int x = 0;
        try {
            Transaction t = session.beginTransaction();
            String hql = "update ApplicantCompanies set companyName = :cname,applicantPosition=:pos,workFrom=:from,"
                    + "workTo=:to where companyId = :cid and applicantId=:apid";
            Query query = session.createQuery(hql);
            query.setString("cname", company.getCompanyName());
            query.setString("pos", company.getApplicantPosition());
            query.setDate("from", company.getWorkFrom());
            query.setDate("to", company.getWorkTo());
            query.setInteger("cid", company.getCompanyId());
            query.setInteger("apid", company.getApplicantId());
            x = query.executeUpdate();
            t.commit();
            System.out.println(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return x;
    }
}
